package com.beiding.v2.test.pg;

import com.beiding.v2.base.IContext;
import com.beiding.v2.base.IUnit;
import com.beiding.v2.base.IUnitHandler;
import com.beiding.v2.element.IValue;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class ValueHandler implements IUnitHandler<IValue> {

    @Override
    public boolean canHandle(IUnit unit) {
        return unit instanceof IValue;
    }

    @Override
    public String handle(IContext context, IValue unit) {
        Object value = unit.getValue();
        return handle(value);
    }

    private String handle(Object value) {
        if (value == null) {
            return "null";
        } else if (value instanceof Boolean) {
            if ((Boolean) value) {
                return "1";
            } else {
                return "0";
            }
        } else if (value instanceof String) {//TODO 为了防止sql注入,对字符串中的双引号转移
            String v = (String) value;
            v = v.replace("\"", "\\\"");
            return "\"" + v + "\"";
        } else if (value instanceof Number) {
            return value.toString();
        } else if (value instanceof Object[]) {//可以用 in
            Object[] vs = (Object[]) value;
            List list = Arrays.asList(vs);
            return this.handle(list);
        } else if (value instanceof Collection) {
            Collection vs = (Collection) value;
            String r = ContentUtils.join(vs, t -> {
                if (t instanceof Object[] || t instanceof Collection) {
                    throw new RuntimeException("禁止参数列嵌套");
                }
                return handle(t);
            }, ",");

            if (r.equals("")) {
                throw new RuntimeException("不接受空白参数列");
            }

            return "(" + r + ")";
        }
        throw new RuntimeException("不支持的值类型:" + value.getClass());

    }

}
